#!/bin/sh
#
# tdclient	This shell script takes care of starting and stopping
#					the Monitor client subsystem .
#
# chkconfig: - 66 35
# description:	monitor client.
# processname: tdclient
# pidfile: /var/run/tdclient/tdclient.pid

# Source function library.
. /etc/rc.d/init.d/functions

#exec="/root/monitor-core/monitor-client/tdclient"
exec="/root/monitor-core/tdclient/tdclient"
prog="tdclient"
lockfile=/var/lock/subsys/$prog
pidfile="/var/run/tdclient/tdclient.pid"

start(){
    [ -x $exec ] || exit 5
    IS_RUNNING=0
    if [ -f "$pidfile" ]; then
	PID=`cat "$pidfile" 2>/dev/null`
	if [ -n "$PID" ] && [ -d "/proc/$PID" ] ; then
	    IS_RUNNING=1
	fi
    fi
	
    if [ $IS_RUNNING = 1 ] ; then
	action $"Starting $prog: " /bin/true
	ret=0
    else
	$exec  >/dev/null 2>&1 &
	ret=1
	sleep 1
	num=`netstat -nlt|grep 9999 | grep -v grep | wc -l`
	if [ $num -ne 0 ];then
		ret=0
	fi
	if [ $ret -eq 0 ]; then
	    action $"Starting $prog: " /bin/true
	    chmod o+r $pidfile >/dev/null 2>&1
	    touch $lockfile
	else
	    action $"Starting $prog: " /bin/false
	fi
    fi
    return $ret
}

stop(){
	if [ ! -f "$pidfile" ]; then
	    action $"Stopping $prog: " /bin/true
	    return 0
	fi
	PID=`cat "$pidfile" 2>/dev/null`
	if [ -n "$PID" ]; then
	    /bin/kill "$PID" >/dev/null 2>&1
	    ret=$?
	    if [ $ret -eq 0 ]; then
		    rm -f $lockfile
		    action $"Stopping $prog: " /bin/true
	    else
			action $"Stopping $prog: " /bin/false
	    fi
	else
	    action $"Stopping $prog: " /bin/false
	    ret=4
	fi
	return $ret
}
 
restart(){
    stop
    start
}




case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart}"
    exit 2
esac

exit $?



